import request from '@/utils/request'
import { getToken } from '@/utils/auth'
import axios from 'axios'
import { EventSourcePolyfill } from 'event-source-polyfill';

// 获取最近五次心率，如果userId不为空则查询指定Id的数据，若为空则自动查询当前登录账号Id的数据
// 前端API配置修改
export function listGetRecentHeartRate(userId) {
  return request({
    url: '/kangyue/userdevicedata/streamLatestData',
    method: 'get',
    params: {
      userId:userId
    }
  })
}
export function listGetRecentSteps(query) {
  return request({
    url: '/kangyue/usersteps/weekStep',
    method: 'get',
    params: query
  })
}
export function listGetRecentSleep(query) {
  return request({
    url: '/kangyue/userdevicedata/sevensleeptime',
    method: 'get',
    params: query
  })
}
// 查询日期范围的数据
export function listGetAll(query) {
  return request({
    url: '/kangyue/userdevicedata/userDataByDate',
    method: 'post',
    // params: query
    data: query,
    headers: {
      'Content-Type': 'application/json'  // 确保发送的数据是 JSON 格式
    }
  })
}
//点击搜索按钮自动查询用户id或设备信息
export function listGetSearchClick() {
  return request({
    url: '/system/user/list',
    method: 'get',
  })
}
export function listGetDevice(userId) {
  return request({
    url: `/kangyue/userdevice/${userId}`, // 使用模板字符串插入userId
    method: 'get',
  })
}
//获取goal数据
export function listGetGoal(userId) {
  return request({
    url: "/health/goals/latestStepGoal",
    method: 'get',
    params: {
      userId:userId
    } // 必须保留空参数对象
  })
}
export function listGetGoal2(userId) {
  return request({
    url: "/health/goals/latestTimeGoal",
    method: 'get',
    params: {
      userId:userId
    } // 必须保留空参数对象
  })
}

// 修改userData.js中的createHeartRateSSE方法
export function createHeartRateSSE(userId) {
  // 使用与request.js相同的getToken方法
  const token = getToken();

  // 使用环境变量中的基础路径
  const baseUrl = process.env.VUE_APP_BASE_API;
  const url = `${baseUrl}/kangyue/userdevicedata/streamLatestData?userId=${userId}`;

  // 保持与axios请求一致的header处理方式
  const emitter = new EventSourcePolyfill(url, {
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'  // 保持与axios默认配置一致
    },
    withCredentials: true  // 保持与axios默认配置一致
  });

  return {
    eventSource: emitter,
    onMessage: (callback) => {
      emitter.addEventListener('message', (event) => {
        try {
          const data = JSON.parse(event.data);
          callback(data);
        } catch (e) {
          console.error('SSE数据解析失败:', e);
        }
      });
    },
    onError: (callback) => {
      emitter.addEventListener('error', (error) => {
        console.error('SSE连接异常:', error);
        callback(error);
        // 添加自动重连逻辑
        if (emmitter.readyState === EventSource.CLOSED) {
          setTimeout(() => this.createHeartRateSSE(userId), 5000);
        }
      });
    }
  };
}

export function listGetWarning(userId) {
  return request({
    url: "/kangyue/UserNotification/usernotification",
    method: 'get',
    params: {
      userId:userId
    } // 必须保留空参数对象
  })
}

export function sendEmail(userId, notifyContent) {
  return request({
    url: '/kangyue/sendSimpleMessage',
    method: 'get',
    params: {  // 保持GET请求参数格式
      UserId: userId,
      notifyContent: notifyContent
    }
  })
}
